#include "croututils.h"
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

void insert_sort_int(int *base, size_t count)
{
    int curr, iter, swap;

    for (curr = 1; curr < count; curr++) {
	swap = base[curr];

	for (iter = curr-1; iter >=0; iter--) {
	    if (base[iter] < swap) {
		break;
	    }
	    base[iter+1] = base[iter];
	}
	base[iter+1] = swap;
    }
}

bool insert_sort(void *base, size_t nobj, size_t size, comparator cmp)
{
    if (base == NULL || cmp == NULL || nobj <= 1 || size < 1) {
	return false;
    }

    char *curr = NULL;
    curr = (char *)malloc(size);
    if (curr == NULL) {
	return false;
    }

    int iptr, iter;
    for (iptr = 1; iptr < nobj; iptr++) {
	/* make backup */
	memcpy(curr, base+iptr*size, size);

	for (iter = iptr-1; iter >= 0; iter--) {
	    if (cmp((char *)base+iter*size, curr) < 0) {
		break;
	    }

	    memcpy((char *)base+(iter+1)*size, (char *)base+iter*size, size);
	}

	memcpy((char *)base+(iter+1)*size, curr, size);
    }

    free(curr);
    return true;
}


#define LENGTH 20
int main(int argc, char **argv)
{
    int buffer[LENGTH];

    randarr_int(buffer, LENGTH);
    listarr_int(buffer, LENGTH);
    insert_sort(buffer, LENGTH, sizeof(buffer[0]), compare_int);
    listarr_int(buffer, LENGTH);

    return 0;
}
